class Solution {
public:
    ListNode* detectCycle(ListNode* head)
    {
        ListNode* fast = head;
        ListNode* slow = head;
        int c = 1;
        while(slow && fast) {
            slow = slow->next;
            fast = fast->next;
            if(fast) {
                fast = fast->next;
            } else {
                return NULL;
            }
            if(slow == fast) {
                fast = slow->next;
                while(fast != slow) {
                    fast = fast->next;
                    c++;
                }
                fast = head;
                slow = head;
                for(int i = 0; i < c; ++i) {
                    fast = fast->next;
                }
                while(fast != slow) {
                    fast = fast->next;
                    slow = slow->next;
                }
                return slow;
            }
        }
        return NULL;
    }
};
